package com.livegoods.service;

import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.commons.pojo.LivegoosMessage;
import com.livegoods.message.LivegoodsMessagePublisher;
import com.livegoods.pojo.House;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class BuyactionServiceImpl implements BuyactionService {


    @Autowired
    private RedisTemplate redisTemplate;


    @Value("${livegoods.redis.houseKey}")
    private String livegoodsRedisHouseKey;
    
    @Value("${livegoods.rabbitmq.buy.exchange}")
    private String exchange;
    
    @Value("${livegoods.rabbitmq.buy.routingKey}")
    private String routingKey;



    
    
    @Autowired
    private LivegoodsMessagePublisher livegoodsMessagePublisher;

    /**
     *
     * 抢购秒杀思路
     *
     * 1，从Redis缓存查询商品数据，并且判断当前商品isRetn状态
     *   true : 没有被抢购，可以抢购
     *   false ：已经被抢购，告诉用户，手慢了，已经抢购完了
     *
     * 2，isRetn 为true ，执行抢购方案
     *  2.1 封装消息对象，将用户id和房屋id封装
     *  2.2 使用mq发送消息，并等待消费者的响应
     * 3，接受消费者响应结果，做出对应处理
     *
     * @param houseId
     * @param username
     * @return
     */

    @Cacheable(cacheNames = "com.livegoods",key = "'details:'+#id")
    @Override
    public LivegoodsResult buyaction(String houseId, String username) {

        // 1，从Redis缓存查询商品数据，并且判断当前商品isRetn状态
                 //   true : 没有被抢购，可以抢购
                 // false ：已经被抢购，告诉用户，手慢了，已经抢购完了
        String redisKey = livegoodsRedisHouseKey+":"+houseId;
        ValueOperations vps = redisTemplate.opsForValue();
        House house  = (House) vps.get(redisKey);

        if(!house.getIsRent()){ //已经抢购完毕
            return LivegoodsResult.error("亲，手慢了，此房屋已经被预定了！！");
        }

        // * 2，isRetn 为true ，执行抢购方案
        //     *  2.1 封装消息对象，将用户id和房屋id封装
        //     
        LivegoosMessage livegoosMessage = new LivegoosMessage();
        livegoosMessage.setUsername(username);
        livegoosMessage.setHouseId(houseId);
            //*  2.2 使用mq发送消息，并等待消费者的响应
        Boolean flag  = (Boolean) livegoodsMessagePublisher.syncSendAndReceiveMessage(exchange, routingKey, livegoosMessage);

        if(flag){
            LivegoodsResult livegoodsResult = LivegoodsResult.ok();
            livegoodsResult.setMsg("恭喜您，预定成功");
            return livegoodsResult;
        }else{
            return LivegoodsResult.error("亲，手慢了，此房屋已经被预定了！！");
        }

    }
}
